<template>
    <div class="uploadImg">
        <el-icon size="40"><Plus /></el-icon>
        <input :accept="accept" type="file" class="upload_ipu" ref="fileLoad" @change="uploadImg" />
        <img v-if="imgSrc" :src="imgSrc" />
    </div>
</template>
<script setup>
import { uploadFile } from '@/api/api';
const emit = defineEmits(['update:imgSrc','uploadSuccess']);
const props = defineProps({
    accept: {
        type: String,
        default: "image/jpg,image/jpeg,image/png,image/gif"
    },
    imgSrc: {
        type: String,
        default: ""
    },
});
const { proxy } = getCurrentInstance();
const imgShow = ref(false);
// const imgSrc = ref('');
function createUrl (file) {
    if (window.URL) {
        return window.URL.createObjectURL(file);
    } else if (window.webkitURL) {
        return window.webkitURL.createObjectURL(file);
    } else {
        return null;
    }
}

async function uploadImg () {
    const file = proxy.$refs.fileLoad.files[0];
    const size = Math.floor(file.size / 1024);
    if (!proxy.accept.includes(file.type.toLowerCase())) {
        proxy.$message.error("Image format is incorrect!");
        return false;
    }
    if (size > 3 * 1024) {
        proxy.$message.error("请上传<3MB的图片");
        return false;
    }
    let form = new FormData();
    form.append("file", file);
    const res = await uploadFile(form);
    // imgSrc.value = this.createUrl(file);
    emit("update:imgSrc", res.msg);
    emit("uploadSuccess", res.msg);
    // imgSrc.value = res.msg;
    // imgShow.value = true;
    // proxy.$message.success("上传成功！");
}
</script>
<style lang="scss" scoped>
.uploadImg {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 180px;
    height: 180px;
    transition: all 0.2s;
    display: flex;
    justify-content: center;
    align-items: center;
    &:hover {
        border-color: #409eff;
    }
    span {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .upload_ipu {
        opacity: 0;
        width: 100%;
        height: 100%;
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        z-index: 2;
    }
    img {
        width: 178px;
        height: 178px;
        position: absolute;
        border-radius: 6px;
        left: 0;
        top: 0;
        z-index: 1;
    }
}
</style>
